package com.shtel.paas.monitorcenter.util.commed;


import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * This class provide interface to execute command on remote Linux.
 */

public class SSHCommandExecutor {


    public static List<Command> list = new ArrayList<>();

    public String ip;
    public String command;
    public String pid;
    public String user;
    public String status;
    public String cpu_use;
    public String cmd;
    public String start_time;
    public String memory_use;
    public int returnCode=0;

    @Value("${sshPath}")
    private String sshPath;

    private String username="patrol";

    private String password="patrol-1";
    
    
    /*String[] commands={"sudo netstat -tlnp |grep :#PORT#| grep -v grep",
    		"ps aux|grep #PID#| grep -v grep "};*/

    public static final int DEFAULT_SSH_PORT = 22;

    private Vector<String> stdout=new Vector<String>();;

    public SSHCommandExecutor(final String ipAddress, final String command) {
        this.ip = ipAddress;
        this.command = command;
    }

    public SSHCommandExecutor(String ip, String command, String username, String password) {
        super();
        this.ip = ip;
        this.command = command;
        this.username = username;
        this.password = password;
    }

    public SSHCommandExecutor execute() throws JSchException {

        JSch jsch = new JSch();
//        jsch.addIdentity("/bmc/.ssh/id_rsa");
        jsch.addIdentity(sshPath);
        MyUserInfo userInfo = new MyUserInfo();
        Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);
        System.out.println(">>getSession by "+ip+" username"+username+" command:"+command);
        session.setPassword(password);
        session.setUserInfo(userInfo);
        session.connect();

        ChannelShell channel = (ChannelShell) session.openChannel("shell");

        channel.connect();
        try {
            // Create and connect session.
            InputStream inputStream = channel.getInputStream();//从远程端到达的所有数据都能从这个流中读取到
            OutputStream outputStream = channel.getOutputStream();//写入该流的所有数据都将发送到远程端。
            //使用PrintWriter流的目的就是为了使用println这个方法
            //好处就是不需要每次手动给字符串加\n
            PrintWriter printWriter = new PrintWriter(outputStream);


            //printWriter.println(commands[0].replace("#PORT#", this.port));
            printWriter.println(command);
            printWriter.flush();

            new Thread(()->{


                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                String msg = null;
                try {
                    Command c = new Command(ip, "");
                    int i = 0;
                    List<String> str = new ArrayList<String>();
                    while((msg = in.readLine())!=null){
                        //System.out.println(msg);
                        i++;
                        if(i>4){
                            if(msg.equals("0")){msg="连接正常";};
                            if(msg.equals("1")){msg="连接失败";};
                            str.add(msg);
                            //c.setCommand(c.getCommand()+"\n"+msg);
                        }
                    }
                    for (int j = 0; j < str.size()-1; j++) {
                        c.setCommand(c.getCommand()+"/n"+str.get(j));
                    }
                    list.add(c);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
            int j=20;
            while(this.pid==null&&j>0){
                Thread.sleep(100L);
                j--;
            }

            if(pid==null){
                channel.disconnect();
                session.disconnect();
                return null;
            }

            //printWriter.println(commands[1].replace("#PID#", this.pid));
            printWriter.println("exit");//加上个就是为了，结束本次交互
            printWriter.flush();




            j=20;
            while(this.cpu_use==null&&j>0){
                Thread.sleep(100L);
                j--;
            }
            if(cpu_use==null){
                channel.disconnect();
                session.disconnect();
                return null;
            }
            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }
            // Disconnect the channel and session.

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            channel.disconnect();
            session.disconnect();

        }
        return this;
    }

    public Vector<String> getStandardOutput() {
        return stdout;
    }


    @Override
    public String toString() {
        return "SSHMultiCommandExecutor [ip=" + ip + ", pid=" + pid + ", status=" + status
                + ", cpu_use=" + cpu_use + ", cmd=" + cmd + ", start_time=" + start_time + ", memory_use=" + memory_use
                + ", returnCode=" + returnCode + "]";
    }


}
